package com.bjpowernode.config;

import com.bjpowernode.config.filter.TokenVerifyFilter;
import com.bjpowernode.config.handler.MyAccessDeniedHandler;
import com.bjpowernode.config.handler.MyAuthenticationFailureHandler;
import com.bjpowernode.config.handler.MyAuthenticationSuccessHandler;
import com.bjpowernode.config.handler.MyLogoutSuccessHandler;
import com.bjpowernode.constant.Constants;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @projectName: code
 * @package: com.bjpowernode.config
 * @className: SecurityConfig
 * @author: Eric
 * @description: TODO
 * @date: 8/5/2024 21:44
 * @version: 1.0
 */

@Configuration
public class SecurityConfig {
    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Resource
    private TokenVerifyFilter tokenVerifyFilter;

    @Resource
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Bean //There is no PasswordEncoder mapped for the id "null"
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,CorsConfigurationSource configurationSource) throws Exception {
        //禁用跨站请求伪造
        return httpSecurity
                .formLogin( (formLogin) -> {
                    formLogin.loginProcessingUrl(Constants.LOGIN_URI)//登陆处理地址，不需要写controller
                            .usernameParameter("loginAct")
                            .passwordParameter("loginPwd")
                            .successHandler(myAuthenticationSuccessHandler)
                            .failureHandler(myAuthenticationFailureHandler);
                })
                .authorizeHttpRequests( (authorize) -> {
                    authorize.requestMatchers(Constants.LOGIN_URI).permitAll()
                            .anyRequest().authenticated();//其它任何请求都需要登录后才能访问
                })
                .csrf(AbstractHttpConfigurer :: disable)//方法引用，禁止跨站请求伪造

                //支持跨域请求
                .cors( (cors) -> {
                    cors.configurationSource(configurationSource);
                })

                //session已经不能使用了，接口的session状态无法保持，将其禁用
                .sessionManagement( (session) ->{
                    //session创建策略
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);//启用无session状态，也就是禁用session
                })

                //添加自定义Filter
                .addFilterAt(tokenVerifyFilter, LogoutFilter.class)

                //退出登录
                .logout((logout) -> {
                    logout.logoutUrl("/api/logout")//退出提交到该地址，该地址不需要写controller，是框架处理
                            .logoutSuccessHandler(myLogoutSuccessHandler);
                })

                .build();
    }

    @Bean
    public CorsConfigurationSource configurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));//来源
        configuration.setAllowedMethods(Arrays.asList("*"));//方法
        configuration.setAllowedHeaders(Arrays.asList("*"));//请求头

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",configuration);
        return source;
    }


}
